<template>
  <section>
    <div>
      <div class="xt-body">
        <div class="xt-left">
          <div class="xt-left-head">{{$t('codingRule.typeTitle')}}</div>
          <div class="xt-left-list">
            <div class="xt-left-list-body bounceInDown animated" :key="index" v-for="(item, index) in ruleCodeList"
                 @click="codingTypeClick(item)" :class="clickTypeId==item.id?'xt-left-list-body-active':''">
              <div style="padding-left: 10px;overflow:hidden;text-overflow: ellipsis;white-space:nowrap;">
                <div class="xt-rule-type"><label>{{item.value}}</label><label :title="item.key" style="font-size: xx-small;line-height: normal;font-weight: 100">({{item.key}})</label></div>
              </div>
            </div>
          </div>
        </div>
        <div class="xt-right">
          <div class="xt-right-head">{{$t('codingRule.ruleTitle')}}</div>
          <div class="xt-right-body" v-show="checkRuleForm.ruleTypeId==0?false:true">
            <div class="xt-coding-edit-content"
                 style="width: 100%;height: 280px;overflow-y: scroll">
              <section class="xt-rule-table">
                <div class="table-item" style="height: 2.5rem;text-align: left;line-height: 2.5rem">
                  <span style="width: 50px;">{{$t('index')}}</span>
                  <span style="width: 13%;">{{$t('codingRule.ruleName')}}</span>
                  <span style="width: 15%;">{{$t('codingRule.ruleType')}}</span>
                  <span style="width: 18%;">{{$t('codingRule.initValue')}}</span>
                  <span style="width: 16%;">{{$t('codingRule.length')}}</span>
                  <span style="width: 16%;">{{$t('codingRule.format')}}</span>
                  <span v-if="getOperation('update|delete')">{{$t('operation')}}</span>
                </div>
                <div>
                  <draggable v-model="ruleElementList" @start="drag=true" @end="drag=false"
                             @change="dragChange">
                    <div :key="index" v-for="(item,index) in ruleElementList" class="table-item">
                      <span style="width: 50px;" class="xt-text-hidden" :title="item.sort">{{item.sort}}</span>
                      <span style="width: 13%;" class="xt-text-hidden" :title="item.ruleName">{{item.ruleName}}</span>
                      <span style="width: 15%;">{{ruleTypeList[item.type - 1].name}}</span>
                      <span style="width: 18%;" class="xt-text-hidden" :title="item.initValue">{{item.initValue}}</span>
                      <span style="width: 16%;" class="xt-text-hidden" :title="item.length">{{item.length}}</span>
                      <span style="width: 16%;" class="xt-text-hidden" :title="item.format">{{item.format}}</span>
                      <span style="display: inline-block;text-align: center;">
                      <el-button size="mini" type="warning" @click="editRule(item)" v-if="getOperation('update')">{{$t('modify')}}</el-button>
                      <el-button size="mini" type="danger" @click="deleteRule(item)" v-if="getOperation('delete')">{{$t('delete')}}</el-button>
                    </span>
                    </div>
                  </draggable>
                </div>
              </section>
            </div>
            <el-button style="margin: 5px" type="primary" size="small" icon="plus" @click="addRuleBtn" v-if="getOperation('insert')">{{$t('add')}}</el-button>

            <div class="xt-preview-box" style="width: 100%;height: 300px;border:1px solid lightgray;margin-top: 0.5rem">
              <div class="xt-right-head">{{$t('codingRule.preview')}}</div>
              <div style="overflow-y: scroll;height: 250px;">
                <div class="xt-coding-item" :key="index" v-for="(item, index) in ruleElementList"
                     style=""
                     @click="divHandle(this)">
                  <span>{{item.initValue > 3 ? item.initValue.slice(0,3) + '...' : item.initValue}}
                    <span style="font-size: xx-small;line-height: normal;font-weight: 100">({{item.ruleName > 3 ? item.ruleName.slice(0,3) + '...' : item.ruleName}})</span></span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--#region 新增修改页面-->
      <!--编码类型新增-->
      <el-dialog width="95%" top="20px" :title="$t('codingRule.add')" :visible.sync="dialog.dialogRuleTypeFormVisible"
                 :close-on-click-modal="false" :modal-append-to-body="false">
        <el-form :model="addRuleTypeForm" :rules="typeRule" ref="typeRule">
          <el-form-item :label="$t('codingRule.key')" label-width="120px" prop="key">
            <el-input v-model="addRuleTypeForm.key" auto-complete="off" :maxlength="20"></el-input>
          </el-form-item>
          <el-form-item :label="$t('codingRule.value')" label-width="120px" prop="value">
            <el-input v-model="addRuleTypeForm.value" auto-complete="off" :disabled="addRuleTypeForm.id!=0" :maxlength="20"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog.dialogRuleTypeFormVisible = false">{{$t('cancel')}}</el-button>
          <el-button type="primary" @click="submitRuleType">{{$t('submit')}}</el-button>
        </div>
      </el-dialog>
      <!--编码规则添加-->
      <el-dialog width="95%" top="20px" :title="checkRuleForm.id==0?$t('codingRule.addRule'):$t('codingRule.modifyRule')"
                 :visible.sync="dialog.addRuleDialogVisible" :close-on-click-modal="false" :modal-append-to-body="false" @close="checkRuleCancel">
        <el-form :model="checkRuleForm" label-width="80px" :rules="rules" ref="rules">
          <el-form-item :label="$t('codingRule.ruleCode')">
            <el-tag type="gray">{{checkRuleForm.ruleCode}}</el-tag>
          </el-form-item>
          <el-form-item :label="$t('codingRule.ruleName')" prop="ruleName">
            <el-input v-model="checkRuleForm.ruleName" auto-complete="off" :maxlength="20"></el-input>
          </el-form-item>
          <el-form-item :label="$t('codingRule.type')" prop="type">
            <el-select v-model="checkRuleForm.type" :placeholder="$t('codingRule.validateType')" @change="changeType(checkRuleForm.type,checkRuleForm,true)" style="width: 100%">
              <el-option :key="index" v-for="(item, index) in ruleTypeList" :label="item.name" :value="item.id"
                         :disabled="getSelectShow(item)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('codingRule.initValue')" prop="initValue">
            <el-input v-model="checkRuleForm.initValue" auto-complete="off" :maxlength="20"></el-input>
          </el-form-item>
          <el-form-item :label="$t('codingRule.length')" v-if="lengthFlag">
            <el-input-number v-model="checkRuleForm.length" :min="0" :max="10" :controls="false"
                             style="width: 100%" :maxlength="10"></el-input-number>
          </el-form-item>
          <el-form-item :label="$t('codingRule.format')" v-if="formatFlag">
            <el-input v-model="checkRuleForm.format" auto-complete="off" :maxlength="20"></el-input>
          </el-form-item>
          <el-form-item :label="$t('index')">
            <el-input-number v-model="checkRuleForm.sort" :min="1" :max="9999" :controls="false"
                             style="width: 100%" :maxlength="20"></el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="checkRuleCancel">{{$t('cancel')}}</el-button>
          <el-button type="primary" @click="checkRuleSubmit" :loading="loading.ruleLoading">{{$t('submit')}}</el-button>
        </div>
      </el-dialog>
      <!--#endregion-->
    </div>
  </section>
</template>

<script>

  /*#region 导入函数*/

  import {CodingRuleAPI, DictAPI} from "../../../modules";
  import draggable from "vuedraggable";
  import {SystemParameterEnum} from "../../../modules/enums";

  /*#endregion*/

  export default {
    methods: {

      /*#region 自定义函数(组件change事件等)*/
      changeType(val, row = Object, addFlag = false) {
        const find = this.ruleTypeList.find((d) => d.id === val);
        if (val) {
          //自增字段
          if (val === 1) {
            this.formatFlag = false;
            this.lengthFlag = true;
            if (addFlag) {
              row.length = find.value.length;
            }
          }
          //时间字段
          if (val === 2) {
            this.formatFlag = true;
            this.lengthFlag = false;
            if (addFlag) {
              row.format = find.value;
            }
          }
          //固定字段
          if (val === 3) {
            this.formatFlag = false;
            this.lengthFlag = false;
          }
          if (addFlag) {
            row.ruleName = find.label;
            row.initValue = find.value;
          }
        }
      },
      checkRuleCancel() {
        this.dialog.addRuleDialogVisible = false;
      },
      divHandle(event) {
        //
      },

      /*#endregion*/

      /*#region 数据提交事件*/
      /*新增编码类型确定事件*/
      submitRuleType() {
        const _this = this;
        this.$refs.typeRule.validate((valid) => {
          if (valid) {
            const para = Object.assign({}, this.addRuleTypeForm);
            para.type = SystemParameterEnum.CodingRuleType;
            if (para.id === 0) {
              DictAPI.insertDict(para).then(({res}) => {
                if (res.data.code === 1) {
                  _this.$message({
                    type: "success",
                    message: this.$t('saveSuccess')
                  });
                  _this.getCodeRuleList();
                  _this.dialog.dialogRuleTypeFormVisible = false;
                } else {
                  _this.$message({
                    type: "error",
                    message: this.$t('saveFail')
                  });
                }
              });
            } else {
              DictAPI.updateDict(para).then(({res}) => {
                if (res.data.code === 1) {
                  _this.$message({
                    type: "success",
                    message: this.$t('saveSuccess')
                  });
                  _this.getCodeRuleList();
                  _this.dialog.dialogRuleTypeFormVisible = false;
                } else {
                  _this.$message({
                    type: "error",
                    message: this.$t('saveFail')
                  });
                }
              });
            }
          }
        });
      },

      //删除编码规则
      deleteRule(item) {
        const _this = this;
        this.$confirm(this.$t('deleteConfirm'), this.$t('tips'), {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: "warning"
        }).then(() => {
          CodingRuleAPI.deleteCodingRule({id: item.id}).then((res) => {
            _this.$message.closeAll();
            if (res.data.code === 1) {
              _this.$message({
                type: "success",
                message: this.$t('deleteSuccess')
              });
              _this.getCodingRule(_this.checkRuleForm.key);
            } else {
              _this.$message({
                type: "error",
                message: this.$t('deleteFail')
              });
            }
          });
        });
      },

      //排序改变
      dragChange(moved) {
        const _this = this;
        this.ruleElementList.map(function (element, index) {
          element.sort = index + 1;
          const param = {id: element.id, sort: element.sort};
          CodingRuleAPI.updateCodingRule(param).then((res) => {
            _this.$message.closeAll();
            if (res.data.code === 1) {
              _this.$message({
                type: "success",
                message: this.$t('saveSuccess')
              });
            } else {
              _this.$message({
                type: "error",
                message: res.data.msg ? res.data.msg : this.$t('saveFail')
              });
            }
          });
        });
      },

      //删除编码类型事件
      deleteRuleType(item) {
        const _this = this;
        this.$confirm(this.$t('deleteConfirm'), this.$t('tips'), {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: "warning"
        }).then(() => {
          DictAPI.deleteDict({id: item.id}).then((res) => {
            _this.$message.closeAll();
            if (res.data.code === 1) {
              _this.$message({
                type: "success",
                message: this.$t('deleteSuccess')
              });
              _this.getCodeRuleList();
            } else {
              _this.$message({
                type: "error",
                message: this.$t('deleteFail')
              });
            }
          });
        });
      },

      /*#endregion*/

      /*#region 操作函数(handle)*/
      //修改编码类型事件
      editRuleType(item) {
        this.addRuleTypeForm = {id: item.id, key: item.key, value: item.value};
        this.dialog.dialogRuleTypeFormVisible = true;
      },
      //打开添加编码类型页面
      addRuleType() {
        this.addRuleTypeForm = {id: 0, key: "", value: ""};
        this.dialog.dialogRuleTypeFormVisible = true;
      },
      //编码规则按钮点击事件
      addRuleBtn(command) {
        if (this.$refs.rules) {
          this.$refs.rules.resetFields();
        }
        this.formatFlag = false;
        this.lengthFlag = false;
        this.checkRuleForm = {
          id: 0,
          key: this.currentRuleKey,
          type: "",
          testId: Math.random(),
          sort: this.ruleElementList.length + 1,
          ruleName: "",
          ruleCode: this.currentRuleCode,
          initValue: "",
          length: 0,
          format: ""
        };
        this.dialog.addRuleDialogVisible = true;
      },
      //修改编码规则
      editRule(item) {
        this.checkRuleForm = item;
        this.changeType(item.type);
        this.dialog.addRuleDialogVisible = true;
      },
      //编码类型点击事件
      codingTypeClick(item) {

        const editCheckRule = this.checkRuleForm;
        editCheckRule.ruleTypeId = item.id;
        editCheckRule.key = item.key;
        editCheckRule.ruleName = item.key;
        editCheckRule.ruleCode = item.value;
        this.clickTypeId = item.id;
        this.currentRuleCode = item.value;
        this.currentRuleKey = item.key;
        this.getCodingRule(item.key);
      },
      //新增/更新规则确定事件
      checkRuleSubmit() {
        const _this = this;
        this.$refs.rules.validate((valid) => {
          if (valid) {
            const para = Object.assign({}, this.checkRuleForm);
            if (para.id === 0) {
              _this.loading.ruleLoading = true;
              CodingRuleAPI.insertCodingRule(para).then((res) => {
                _this.$message.closeAll();
                if (res.data.code === 1) {
                  _this.$message({
                    type: "success",
                    message: this.$t('saveSuccess')
                  });
                  _this.getCodingRule(para.key);
                  _this.dialog.addRuleDialogVisible = false;
                } else {
                  _this.$message({
                    type: "error",
                    message: this.$t('saveFail')
                  });
                }
                _this.loading.ruleLoading = false;
              });
            } else {
              _this.loading.ruleLoading = true;
              CodingRuleAPI.updateCodingRule(para).then((res) => {
                _this.$message.closeAll();
                if (res.data.code === 1) {
                  _this.$message({
                    type: "success",
                    message: this.$t('saveSuccess')
                  });
                  _this.getCodingRule(para.key);
                  _this.dialog.addRuleDialogVisible = false;
                } else {
                  _this.$message({
                    type: "error",
                    message: this.$t('saveFail')
                  });
                }
                _this.loading.ruleLoading = false;
              });
            }
          }
        });
      },

      /*#endregion*/

      /*#region 获取数据*/
      //选择框判断
      getSelectShow(item) {
        const _this = this;
        if (item.id === 3) {
          return false;
        } else {
          const selectedItem = _this.ruleElementList.find((element) => item.id === element.type);
          if (selectedItem) {
            return true;
          } else {
            return false;
          }
        }
      },
      //获取编码类型
      getCodeRuleList() {
        DictAPI.listDict({
          type: SystemParameterEnum.CodingRuleType,
          pageIndex: 1,
          pageSize: 2147483647,
          orderBy: "`Key` Asc"
        }).then(({res, list}) => {
          this.ruleCodeList = list || [];
        });
      },

      //获取编码规则列表
      getCodingRule(ruleCode) {
        const _this = this;
        ruleCode = ruleCode || "";
        CodingRuleAPI.listCodingRule({key: ruleCode}).then((res) => {
          if (res.data.code === 1) {
            let list = res.data.data.data;
            list = list.sort((a, b) => a.sort - b.sort);
            list.map(function (element) {
              element.testId = Math.random();
            });
            _this.ruleElementList = res.data.data.data;
          }
        });
      }

      /*#endregion*/
    },

    /*#region 生命周期函数(created、mount、等)*/
    mounted() {
      this.getCodeRuleList();
    },

    /*#endregion*/
    /*#region 注册绑定数据*/
    components: {draggable},
    data() {
      return {
        ruleCodeList: [], //编码类型列表
        typeRule: {//编码类型表单验证
          key: [{required: true, message: this.$t('codingRule.validateKey'), trigger: "blur"}, {pattern: /^\S.*?$/, message: this.$t('codingRule.emptyHead')}],
          value: [{required: true, message: this.$t('codingRule.validateValue'), trigger: "blur"}, {pattern: /^\S.*?$/, message: this.$t('codingRule.emptyHead')}]
        },
        rules: {
          ruleName: [{pattern: /^\S.*?$/, message: this.$t('codingRule.emptyHead')}, {required: true, message: this.$t('codingRule.validateRuleName'), trigger: "blur"}],
          initValue: [{pattern: /^\S.*?$/, message: this.$t('codingRule.emptyHead')}, {required: true, message: this.$t('codingRule.validateInitValue'), trigger: "blur"}],
          type: [{pattern: /^\S.*?$/, message: this.$t('codingRule.emptyHead')}, {
            required: true,
            type: "number",
            message: this.$t('codingRule.validateType'),
            trigger: "blur"
          }]
        },
        currentRuleCode: "",
        currentRuleKey: "",
        ruleTypeList: [
          {id: 1, name: this.$t('codingRule.addField'), disabled: false, value: "0001", label: this.$t('codingRule.addFieldTop')},
          {id: 2, name: this.$t('codingRule.dateField'), disabled: false, value: "yyyyMMdd", label: this.$t('codingRule.timeField')},
          {id: 3, name: this.$t('codingRule.fixedField'), disabled: false, value: "", label: this.$t('codingRule.preX')}
        ],
        ruleElementList: [], //编码规则列表
        checkRuleForm: {
          id: 0,
          key: "",
          ruleTypeId: 0,
          ruleName: "",
          ruleType: "",
          initValue: "",
          length: 0,
          format: "",
          sort: 1,
          CodeTypeName: "",
          ruleTypeCode: "",
          type: 1
        }, //添加规则模态框
        addRuleTypeForm: {id: 0, key: "", value: ""}, //添加编码规则类型
        dialog: {addRuleDialogVisible: false, dialogRuleTypeFormVisible: false}, //弹框页面显示
        loading: {ruleLoading: false},
        formatFlag: false,
        lengthFlag: false,
        clickTypeId: null
      };
    }

    /*#endregion*/
  };
</script>

<style scoped>
  .xt-left {
    display: inline-block;
    float: left;
    width: 20%;
    height: 700px;
    /*background-color: #EAECF0;*/
    border: 1px solid #E4E8F1;
  }

  .xt-left-head {
    height: 3rem;
    font-weight: bolder;
    font-size: 16px;
    line-height: 3rem;
    /*color:#ffffff;*/
    text-align: center;
    background-color: #EEF1F6;
  }

  .xt-left-list {
    height: 700px;
    overflow: auto;
  }

  .xt-rule-type {
    display: inline-block;
  }

  .xt-left-list-body {
    height: 3rem;
    line-height: 3rem;
    /*margin-bottom: 0.2rem;*/
    text-align: left;
    /*background-color: #f292b2;*/
    border-bottom: 1px solid #E4E8F1;
  }

  .xt-left-list-body:hover {
    background-color: #EEF1F6;
    /*color:#ffffff*/
  }

  .xt-left-list-add {
    height: 3rem;
    line-height: 3rem;
    text-align: center;
    border-bottom: 1px solid #E4E8F1;
  }

  .xt-left-list-body-active {
    background-color: #EDF7FF;
    /*color:#ffffff*/
  }

  .xt-right {
    display: inline-block;
    width: 78%;
    height: 700px;
    /*background-color: orange;*/
    border: 1px solid #E4E8F1;
  }

  .xt-right-head {
    height: 48px;
    font-weight: bolder;
    font-size: 16px;
    line-height: 3rem;
    /*color:#ffffff;*/
    text-align: center;
    background-color: #EEF1F6;
  }

  .xt-right-body {
    padding: 0.2rem 0.3rem;
  }

  .xt-coding-item {
    /* cursor: move; */
    /*width: 100;*/
    padding: 0 10px;
    height: 50px;
    background-color: #b9f0b2;
    display: inline-block;
    float: left;
    margin: 0.25rem 0.25rem 0 0.3rem;
    line-height: 50px;
    text-align: center;
    font-size: large;
    font-weight: bolder;
  }

  .xt-rule-table {
    border-top: 1px solid #b4b4b4;
    border-left: 1px solid #b4b4b4;
  }

  .xt-rule-table .table-item {
    border-bottom: 1px solid #b4b4b4;
    border-right: 1px solid #b4b4b4;
    cursor: move;
  }

  .xt-rule-table .table-item span {
    display: inline-block;
    text-align: center;
    padding-top: 5px;
    padding-bottom: 5px;
  }

  .xt-rule-table .table-item:hover {
    background: #f0f0f0;
  }

</style>
